package com.example.cc.client.listeners;

import cn.hutool.core.util.StrUtil;
import com.example.cc.client.manager.GenericCacheManager;
import com.example.cc.client.properties.ConfigCenterProperties;
import com.example.cc.client.refresh.PropertyRefresher;
import com.example.cc.common.dto.ChangeEventMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 变更监听器
 */
@SuppressWarnings("all")
@Component
@RequiredArgsConstructor
@Slf4j
public class ConfigChangeListener {

    @Resource
    private GenericCacheManager<String, Object> cacheManager;

    private final ConfigCenterProperties configCenterProperties;

    private final PropertyRefresher propertyRefresher;

    @Value("#{T(com.example.cc.common.rabbitmq.RabbitConstants).CLIENT_QUEUE_PREFIX + configCenterProperties.getClientId()}")
    private String queueName;

    @PostConstruct
    public void init() {
    }

    // @RabbitListener(queues = "#{T(com.example.cc.common.rabbitmq.RabbitConstants).CLIENT_QUEUE_PREFIX + configCenterProperties.getClientId()}")
    public void handleChange(ChangeEventMessage message) {
        if (message != null && StrUtil.isNotBlank(message.getKey())) {
            propertyRefresher.doRefresh(message.getKey(), message.getValue());
            switch (message.getAction()) {
                case CREATE:
                    handleCreate(message.getKey(), message.getValue());
                case UPDATE:
                    handleUpdate(message.getKey(), message.getValue());
                    break;
                case DELETE:
                    handleDelete(message.getKey());
                    break;
                default:
                    System.out.println("不支持的Action: " + message.getAction());
            }
        }
    }

    private void handleCreate(String key, Object value) {
        log.info("新增 {} : {}", key, value);
        cacheManager.update(key, value);
    }

    private void handleUpdate(String key, Object value) {
        log.info("更新 {} : {}", key, value);
        cacheManager.update(key, value);
    }

    private void handleDelete(String key) {
        log.info("删除 {}", key);
        cacheManager.delete(key);
    }

}
